package com.alibaba.citrus.cr.platform.enhance.facade.service.inventoryAllot;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.exception.FacadeException;
import com.alibaba.citrus.cr.common.util.DateUtils;
import com.alibaba.citrus.cr.common.util.PageUtils;
import com.alibaba.citrus.cr.platform.enhance.repository.InventoryAllotLineRepository;
import com.alibaba.citrus.cr.platform.enhance.repository.InventoryAllotQueryRepository;
import com.alibaba.cz.base.tool.Nullable;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.BaselineQueryScItemByPageFromDbRequest;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.crplatformenhance.enums.InventoryAllotTypeEnum;
import com.epoch.app.crplatformenhance.inventoryallot.dto.QueryListRequest;
import com.epoch.app.crplatformenhance.inventoryallot.model.InventoryAllot;
import com.epoch.app.crplatformenhance.inventoryallotline.model.InventoryAllotLine;
import com.epoch.app.crplatformenhance.inventoryallotquery.service.InventoryAllotQueryService;
import com.epoch.app.crplatformenhance.model.dto.*;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

@Component
@Primary
public class InventoryAllotQueryServiceImpl implements InventoryAllotQueryService {
    private static Log log = Log.getLogger(InventoryAllotQueryServiceImpl.class);

    @Autowired
    private InventoryAllotQueryRepository inventoryAllotQueryRepository;

    @Autowired
    private InventoryAllotLineRepository inventoryAllotLineRepository;

    @Autowired
    private CrPlatformEnhanceService crPlatformEnhanceService;

    @Autowired
    private BaseDataService baseDataService;

    private final static String WAREHOUSE_IDS = "wareHouseIds";

    private static final Integer MAX_PAGE_SIZE = 2000;

    @Override
    public Result<List<InventoryAllotSDO>> pageQueryInventoryAllot(PageQueryInventoryAllotRequest pageQueryInventoryAllotRequest) {

        Result<List<InventoryAllotSDO>> result = inventoryAllotQueryRepository.pageQuery(pageQueryInventoryAllotRequest);
        List<InventoryAllotSDO> list = result.getResult();
        if (CollectionUtils.isEmpty(list)) {
            return Result.listSuccess(null, 0);
        }
        list.forEach(x -> {
            Map empMap = JSONObject.parseObject(x.getCreator(), HashMap.class);
            x.setCreatorId((String) empMap.get("realName"));
        });
        // same organization-allotDate should invalid status
        Map<String, List<InventoryAllotSDO>> orgMap = Nullable.stream(list).collect(Collectors.groupingBy(o->o.getOrganizationCode()+""+o.getInventoryAllotDate()));

        for (Map.Entry<String, List<InventoryAllotSDO>> orgAllotEntry : orgMap.entrySet()) {
            List<InventoryAllotSDO> value = orgAllotEntry.getValue();
            List<InventoryAllotSDO> shouldInvalidIList = value.subList(1, value.size());
            if (CollectionUtils.isNotEmpty(shouldInvalidIList)){
                shouldInvalidIList.forEach(o->{
                    Map<String, String> statusLabel = new HashMap<>();
                    o.setStatus("已失效");
                    statusLabel.put("text", "已失效");
                    statusLabel.put("type", "cancel");
                    o.setStatusLabel(statusLabel);});
            }

        }

        return Result.listSuccess(list, result.getTotal());

    }

    @Override
    @FacadeInvoker
    public Result<InventoryAllotSDO> queryById(InventoryAllotQueryByIdRequest inventoryAllotQueryByIdRequest) {

        List<String> scItemIdList = Lists.newArrayList();
        //货品编码不为空时需要模糊查询出货品id
        if (org.apache.commons.lang3.StringUtils.isNotBlank(inventoryAllotQueryByIdRequest.getScItemCode())){
            //货品编码长度不能超过50
            if (inventoryAllotQueryByIdRequest.getScItemCode().length() > 50){
                throw new FacadeException("OTS-06-005-00-15-025");
            }
            //根据货品编码模糊查出所有货品id
            List<String> scItemIds = getScItemIdListByFuzzyQueryScItemCode(inventoryAllotQueryByIdRequest.getScItemCode());
            if (CollectionUtils.isNotEmpty(scItemIds)){
                scItemIdList.addAll(scItemIds);
            }
        }
        //兼容之前单个货品id查询
        if (org.apache.commons.lang3.StringUtils.isNotBlank(inventoryAllotQueryByIdRequest.getScItemId())){
            scItemIdList.add(inventoryAllotQueryByIdRequest.getScItemId());
        }
        //兼容下如果scItemIdList里有数据的话 也加进去;
        if (CollectionUtils.isNotEmpty(inventoryAllotQueryByIdRequest.getScItemIdList())){
            scItemIdList.addAll(inventoryAllotQueryByIdRequest.getScItemIdList());
        }
        //如果scItemId或者scItemCode 不全部为空 并且 货品id列表为空(即模糊查询货品编码结果为空)
        if (!org.apache.commons.lang3.StringUtils.isAllBlank(inventoryAllotQueryByIdRequest.getScItemCode(),inventoryAllotQueryByIdRequest.getScItemId())
                && CollectionUtils.isEmpty(scItemIdList)){
            return Result.success(null);
        }
        if (CollectionUtils.isNotEmpty(scItemIdList)){
            inventoryAllotQueryByIdRequest.setScItemIdList(scItemIdList);
        }
        return inventoryAllotQueryRepository.queryById(inventoryAllotQueryByIdRequest);
    }

    @Override
    public Result<List<InventoryAllotExcelExportResponse>> excelExport(PageQueryInventoryAllotRequest request) {
        if (StringUtils.isBlank(request.getOrgId())) {
            List<String> orgs = getOrgList();
            request.setOrgIds(orgs);
        }
        Result<List<InventoryAllotExcelExportResponse>> result = inventoryAllotQueryRepository.excelExPort(request);
        return result;
    }

    private List<String> getOrgList() {
        StrategyOrganizationSelectRequest query = new StrategyOrganizationSelectRequest();
        query.setType(104);
        StrategyOrganizationSelectResponse response = crPlatformEnhanceService.strategyOrganizationSelect(query);
        Object object = response.getResult();
        List<String> orgList = new ArrayList<>();
        if (object instanceof ArrayList<?>) {
            for (Object o : (List<?>) object) {
                Map<String, String> jsonObject = (Map) (o);
                orgList.add(jsonObject.get("value"));
            }
        }
        return orgList;
    }

    @Override
    @FacadeInvoker
    public Result<QueryAllotResponse> queryAllot(QueryAllotRequest queryAllotRequest) {
        QueryAllotResponse response = new QueryAllotResponse();

        QueryListRequest queryListRequest = new QueryListRequest();
        queryListRequest.setOrganizationCode(queryAllotRequest.getOrganizationCode());

        //业务员

        queryListRequest.setDistributionType(InventoryAllotTypeEnum.SALESMAN.getCode());
        Result<InventoryAllot> inventoryAllotResult = inventoryAllotQueryRepository.queryList(queryListRequest);
        if (inventoryAllotResult.getResult() != null && StringUtils.isNotBlank(queryAllotRequest.getSalesmanCode())) {
            InventoryAllot inventoryAllot = inventoryAllotResult.getResult();
            //比较每日生效起止时间
            if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot,queryAllotRequest.getWarehouseCode())) {
                InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                request.setInventoryAllotId(inventoryAllot.getId().toString());
                request.setScItemIdList(queryAllotRequest.getScItemId() == null ? null : Collections.singletonList(queryAllotRequest.getScItemId()));
                request.setDimensionId(queryAllotRequest.getSalesmanCode());
                Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                    InventoryAllotLine inventoryAllotLine = listResult.getResult().get(0);
                    response.setId(inventoryAllotLine.getId().toString());
                    response.setDistributionQuantity(inventoryAllotLine.getDistributionQuantity());
                    response.setRemainingQuantity(inventoryAllotLine.getRemainingQuantity());
                    response.setSyncVersion(inventoryAllotLine.getSyncVersion());
                    response.setMainAllotId(String.valueOf(inventoryAllot.getId()));
                    response.setMainLimitSwitch(inventoryAllot.getLimitSwitch());
                    return Result.success(response);
                }
            }
        }

        queryListRequest.setDistributionType(InventoryAllotTypeEnum.DEPARTMENT.getCode());
        Result<InventoryAllot> departmentResult = inventoryAllotQueryRepository.queryList(queryListRequest);
        if (departmentResult.getResult() != null && StringUtils.isNotBlank(queryAllotRequest.getDepartmentCode())) {
            InventoryAllot inventoryAllot = departmentResult.getResult();
            if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot,queryAllotRequest.getWarehouseCode())) {
                InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                request.setInventoryAllotId(inventoryAllot.getId().toString());
                request.setScItemIdList(queryAllotRequest.getScItemId() == null ? null : Collections.singletonList(queryAllotRequest.getScItemId()));
                request.setDimensionId(queryAllotRequest.getDepartmentCode());
                Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                    InventoryAllotLine inventoryAllotLine = listResult.getResult().get(0);
                    response.setId(inventoryAllotLine.getId().toString());
                    response.setDistributionQuantity(inventoryAllotLine.getDistributionQuantity());
                    response.setRemainingQuantity(inventoryAllotLine.getRemainingQuantity());
                    response.setSyncVersion(inventoryAllotLine.getSyncVersion());
                    response.setMainAllotId(String.valueOf(inventoryAllot.getId()));
                    response.setMainLimitSwitch(inventoryAllot.getLimitSwitch());
                    return Result.success(response);
                }
            }
        }

        queryListRequest.setDistributionType(InventoryAllotTypeEnum.CHANNEL.getCode());
        Result<InventoryAllot> channelResult = inventoryAllotQueryRepository.queryList(queryListRequest);
        if (channelResult.getResult() != null && StringUtils.isNotBlank(queryAllotRequest.getChannelCode())) {
            InventoryAllot inventoryAllot = channelResult.getResult();
            if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot,queryAllotRequest.getWarehouseCode())) {
                InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                request.setInventoryAllotId(inventoryAllot.getId().toString());
                request.setScItemIdList(queryAllotRequest.getScItemId() == null ? null : Collections.singletonList(queryAllotRequest.getScItemId()));
                request.setDimensionId(queryAllotRequest.getChannelCode());
                Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                    InventoryAllotLine inventoryAllotLine = listResult.getResult().get(0);
                    response.setId(inventoryAllotLine.getId().toString());
                    response.setDistributionQuantity(inventoryAllotLine.getRemainingQuantity());
                    response.setRemainingQuantity(inventoryAllotLine.getRemainingQuantity());
                    response.setSyncVersion(inventoryAllotLine.getSyncVersion());
                    response.setMainAllotId(String.valueOf(inventoryAllot.getId()));
                    response.setMainLimitSwitch(inventoryAllot.getLimitSwitch());
                    return Result.success(response);
                }
            }
        }
        return Result.success(null);
    }

    private static Boolean checkTime(InventoryAllot inventoryAllot) {
        if (inventoryAllot == null) {
            return false;
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        SimpleDateFormat simpleDateFormatDay = new SimpleDateFormat("yyyy:MM:dd");

        Long now = null;
        Long beginTime = null;
        Long endTime = null;
        try {
            if (!simpleDateFormatDay.format(new Date()).equalsIgnoreCase(simpleDateFormatDay.format(inventoryAllot.getInventoryAllotTime()))) {
              return false;
            }

            now = simpleDateFormat.parse(simpleDateFormat.format(new Date())).getTime();
//            log.info("begintime:{},endtime:begin{}", inventoryAllot.getDailyBeginTime(), inventoryAllot.getDailyEndTime());
            //没有开始或截止时间，算无效
            if(Objects.isNull(inventoryAllot.getDailyBeginTime()) || Objects.isNull(inventoryAllot.getDailyEndTime())){
                return false;
            }
            beginTime = simpleDateFormat.parse(inventoryAllot.getDailyBeginTime()).getTime();
            endTime = simpleDateFormat.parse(inventoryAllot.getDailyEndTime()).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (now.compareTo(endTime) < 0 && now.compareTo(beginTime) > 0) {
            return true;
        }
        return false;
    }


    @FacadeInvoker
    @Override
    public Result<QueryResolveInventoryResponse> batchQueryAllot(BatchQueryAllotRequest queryAllotRequest) {
        if (Objects.isNull(queryAllotRequest)) {
            return Result.fail("SYS_ERR_INVALID_PARAM", "系统错误，方法参数有误");
        }
        QueryResolveInventoryResponse resp = new QueryResolveInventoryResponse();
        Map<String, String> itemDailyInventory = new HashMap<>();
        Map<String, String> itemDailySumDeduct = new HashMap<>();
        Map<String, Boolean> itemDailyLimit = new HashMap<>();
        QueryListRequest queryListRequest = new QueryListRequest();
        queryListRequest.setOrganizationCode(queryAllotRequest.getOrganizationCode());

        //业务员
        if (queryAllotRequest.getSalesmanCode() != null) {
            queryListRequest.setDistributionType(InventoryAllotTypeEnum.SALESMAN.getCode());
            try {
                Result<InventoryAllot> inventoryAllotResult = inventoryAllotQueryRepository.queryList(queryListRequest);

                if (Objects.nonNull(inventoryAllotResult) && Objects.nonNull(inventoryAllotResult.getResult())) {
                    InventoryAllot inventoryAllot = inventoryAllotResult.getResult();
                    Boolean limitSwitch = inventoryAllot.getLimitSwitch();
                    //比较每日生效起止时间
                    if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot,queryAllotRequest.getWarehouseCode())) {
                    //if (checkTime(inventoryAllot) ) {
                        InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                        request.setInventoryAllotId(inventoryAllot.getId().toString());
                        request.setScItemIdList(queryAllotRequest.getScItemList());
                        request.setDimensionId(queryAllotRequest.getSalesmanCode());
                        request.setStart(0);
                        request.setLimit(1000);
                        Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                            listResult.getResult().forEach(inventoryAllotLine -> {
                                if (!itemDailyInventory.containsKey(inventoryAllotLine.getScItemId()) || "0".equals(itemDailyInventory.get(inventoryAllotLine.getScItemId()))) {
                                    Double distributionQuantity = inventoryAllotLine.getDistributionQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getDistributionQuantity());
                                    Double remainingQuantity = inventoryAllotLine.getRemainingQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getRemainingQuantity());
                                    itemDailyInventory.put(inventoryAllotLine.getScItemId(), inventoryAllotLine.getRemainingQuantity());
                                    itemDailySumDeduct.put(inventoryAllotLine.getScItemId(), String.valueOf(distributionQuantity - remainingQuantity));
                                    itemDailyLimit.put(inventoryAllotLine.getScItemId(),limitSwitch);

                                }
                            });
                            resp.setDailyInventoryMap(itemDailyInventory);
                            resp.setDailyInventoryDeductMap(itemDailySumDeduct);
                            resp.setDailyInventoryLimitMap(itemDailyLimit);
                            return Result.success(resp);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询业务员分配单异常:"+queryAllotRequest.getSalesmanCode());
            }
        }

        if (queryAllotRequest.getDepartmentCode() != null) {
            queryListRequest.setDistributionType(InventoryAllotTypeEnum.DEPARTMENT.getCode());
            try {
                Result<InventoryAllot> departmentResult = inventoryAllotQueryRepository.queryList(queryListRequest);

                if (Objects.nonNull(departmentResult) && Objects.nonNull(departmentResult.getResult())) {
                    InventoryAllot inventoryAllot = departmentResult.getResult();
                    Boolean limitSwitch = inventoryAllot.getLimitSwitch();
                    if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot, queryAllotRequest.getWarehouseCode())) {
                        InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                        request.setInventoryAllotId(inventoryAllot.getId().toString());
                        request.setScItemIdList(queryAllotRequest.getScItemList());
                        request.setDimensionId(queryAllotRequest.getDepartmentCode());
                        request.setStart(0);
                        request.setLimit(1000);
                        Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                        if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                            listResult.getResult().forEach(inventoryAllotLine -> {
                                if (!itemDailyInventory.containsKey(inventoryAllotLine.getScItemId()) || "0".equals(itemDailyInventory.get(inventoryAllotLine.getScItemId()))) {
                                    Double distributionQuantity = inventoryAllotLine.getDistributionQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getDistributionQuantity());
                                    Double remainingQuantity = inventoryAllotLine.getRemainingQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getRemainingQuantity());
                                    itemDailyInventory.put(inventoryAllotLine.getScItemId(), inventoryAllotLine.getRemainingQuantity());
                                    itemDailySumDeduct.put(inventoryAllotLine.getScItemId(), String.valueOf(distributionQuantity - remainingQuantity));
                                    itemDailyLimit.put(inventoryAllotLine.getScItemId(),limitSwitch);
                                }
                            });
                            resp.setDailyInventoryMap(itemDailyInventory);
                            resp.setDailyInventoryDeductMap(itemDailySumDeduct);
                            resp.setDailyInventoryLimitMap(itemDailyLimit);

                            return Result.success(resp);
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("查询部门分配单异常:"+queryAllotRequest.getDepartmentCode());
            }

        }
        if (queryAllotRequest.getChannelCode() != null) {
            queryListRequest.setDistributionType(InventoryAllotTypeEnum.CHANNEL.getCode());
            try{
                Result<InventoryAllot> channelResult = inventoryAllotQueryRepository.queryList(queryListRequest);
                if (Objects.nonNull(channelResult)&& Objects.nonNull(channelResult.getResult())) {
                    InventoryAllot inventoryAllot = channelResult.getResult();
                    Boolean limitSwitch = inventoryAllot.getLimitSwitch();
                    if (checkTime(inventoryAllot) && checkDimensionWarehouseCode(inventoryAllot, queryAllotRequest.getWarehouseCode())) {
                        InventoryAllotLineLoadListRequest request = new InventoryAllotLineLoadListRequest();
                        request.setInventoryAllotId(inventoryAllot.getId().toString());
                        request.setScItemIdList(queryAllotRequest.getScItemList());
                        request.setDimensionId(queryAllotRequest.getChannelCode());
                        request.setStart(0);
                        request.setLimit(1000);
                        Result<List<InventoryAllotLine>> listResult = inventoryAllotLineRepository.queryAllotList(request);
                        if (CollectionUtils.isNotEmpty(listResult.getResult())) {
                            listResult.getResult().forEach(inventoryAllotLine -> {
                                if (!itemDailyInventory.containsKey(inventoryAllotLine.getScItemId()) || "0".equals(itemDailyInventory.get(inventoryAllotLine.getScItemId()))) {
                                    Double distributionQuantity = inventoryAllotLine.getDistributionQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getDistributionQuantity());
                                    Double remainingQuantity = inventoryAllotLine.getRemainingQuantity() == null ? 0 : Double.parseDouble(inventoryAllotLine.getRemainingQuantity());
                                    itemDailyInventory.put(inventoryAllotLine.getScItemId(), inventoryAllotLine.getRemainingQuantity());
                                    itemDailySumDeduct.put(inventoryAllotLine.getScItemId(), String.valueOf(distributionQuantity - remainingQuantity));
                                    itemDailyLimit.put(inventoryAllotLine.getScItemId(),limitSwitch);
                                }
                            });

                            resp.setDailyInventoryMap(itemDailyInventory);
                            resp.setDailyInventoryDeductMap(itemDailySumDeduct);
                            resp.setDailyInventoryLimitMap(itemDailyLimit);
                            return Result.success(resp);
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("查询渠道分配单异常:"+queryAllotRequest.getChannelCode());
            }

        }
        return Result.success(null);
    }

    private boolean checkDimensionWarehouseCode(InventoryAllot inventoryAllot, String warehouseCode) {
        // 校验每日库存分解仓库编码是否为空
        if (StringUtils.isBlank(inventoryAllot.getFeatures())) {
            log.info("checkDimensionWarehouseCode|step1:" + "每日库存分解仓库编码为空");
            return Boolean.FALSE;
        }
        Map<String, String> map = JSONObject.parseObject(inventoryAllot.getFeatures(), new TypeReference<Map<String, String>>() {
        });
        if (StringUtils.isBlank(map.get(WAREHOUSE_IDS))) {
            log.info("checkDimensionWarehouseCode|step2:" + "每日库存分解仓库编码为空");
            return Boolean.FALSE;
        }
        if (StringUtils.isBlank(inventoryAllot.getDistributionId()) || StringUtils.isBlank(warehouseCode)) {
            log.info("checkDimensionWarehouseCode|step3:" + "每日库存分解id为空或仓库编码为空");
            return Boolean.FALSE;
        }
        List<String> wareHouseIds = JSONObject.parseObject(map.get(WAREHOUSE_IDS), new TypeReference<List<String>>() {
        });
        if(wareHouseIds.contains(warehouseCode)) {
            return Boolean.TRUE;
        }
        log.info("checkDimensionWarehouseCode|step4|仓库列表:" + wareHouseIds + "|未找到对应仓库编码:"+warehouseCode);
        return Boolean.FALSE;
    }

    @Override
    public Result<List<DailyInventoryLine>> queryAllotOrderLineById(QueryDailyAllotOrderLine queryDailyAllotOrderLine){
        InventoryAllotLineLoadListRequest lineLoadListRequest = new InventoryAllotLineLoadListRequest();
        lineLoadListRequest.setAllotLineIdList(queryDailyAllotOrderLine.getAllotLineIdList());
        Result<List<InventoryAllotLine>> result = inventoryAllotLineRepository.queryAllotList(lineLoadListRequest);
        List<DailyInventoryLine> dailyInventoryLines = new ArrayList<>();
        if (result != null && CollectionUtils.isNotEmpty(result.getResult())){
            Set<String> allotIds = result.getResult().stream().map(InventoryAllotLine::getInventoryAllotId).collect(Collectors.toSet());
            List<String> allots = new ArrayList<>(allotIds);
            QueryAllotListRequest queryAllotListRequest = new QueryAllotListRequest();
            queryAllotListRequest.setIdList(allots);
            Map<String,Boolean> allotBoolean = new HashMap<>();
            Result<List<InventoryAllot>> allotResult = inventoryAllotQueryRepository.queryAllotListByCondition(queryAllotListRequest);
            if (allotResult != null && CollectionUtils.isNotEmpty(allotResult.getResult())){
                //校验分配日期和每日时间
                Date date = new Date();
                allotResult.getResult().forEach(inventoryAllot -> {
//                    checkTime(inventoryAllot);
//                    date.after(DateUtils.getFirstTime(inventoryAllot.getInventoryAllotTime()));
//                    date.before(DateUtils.getLatestTime(inventoryAllot.getInventoryAllotTime()));
                    if (checkTime(inventoryAllot) && date.after(DateUtils.getFirstTime(inventoryAllot.getInventoryAllotTime())) &&
                            date.before(DateUtils.getLatestTime(inventoryAllot.getInventoryAllotTime()))){
                        allotBoolean.put(inventoryAllot.getId().toString(),true);
                    }else {
                        allotBoolean.put(inventoryAllot.getId().toString(),false);
                    }
                });
            }
            result.getResult().forEach(inventoryAllotLine -> {
                DailyInventoryLine line = new DailyInventoryLine();
                BigDecimal dis = new BigDecimal(inventoryAllotLine.getDistributionQuantity());
                BigDecimal remain = new BigDecimal(inventoryAllotLine.getRemainingQuantity());
                BigDecimal used = dis.subtract(remain).setScale(3, RoundingMode.DOWN);
                line.setLineId(String.valueOf(inventoryAllotLine.getId()));
                line.setDistributeQuantity(inventoryAllotLine.getDistributionQuantity());
                line.setRemainQuantity(inventoryAllotLine.getRemainingQuantity());
                line.setSubstractQuantity(used.toString());
                line.setValid(allotBoolean.get(inventoryAllotLine.getInventoryAllotId()) != null && allotBoolean.get(inventoryAllotLine.getInventoryAllotId()));
                dailyInventoryLines.add(line);
            });
        }
        return Result.listSuccess(dailyInventoryLines,dailyInventoryLines.size());
    }


    /**
     * 货品编码模糊查询货品id
     * @param scItemCode
     * @return
     */
    private List<String> getScItemIdListByFuzzyQueryScItemCode(String scItemCode){
        if (org.apache.commons.lang3.StringUtils.isBlank(scItemCode)){
            return null;
        }
        BaselineQueryScItemByPageFromDbRequest dbRequest = new BaselineQueryScItemByPageFromDbRequest();
        dbRequest.setOutId(scItemCode);
        dbRequest.setBusinessType("11");//业态常温
        dbRequest.setType(0);//非组合货品
        dbRequest.setLimit(MAX_PAGE_SIZE);
        Object scItemResult = baseDataService.baselineQueryScItemByPageFromDb(dbRequest);
        //获取总条数
        Integer total = getScItemTotalSize(scItemResult);
        List<String> scItemIds = Lists.newArrayList();
        if (total > MAX_PAGE_SIZE){
            Integer totalPage = PageUtils.getTotalPage(total, MAX_PAGE_SIZE);
            //超过最大条数后 先放入第一页的货品id
            Optional.ofNullable(getScItemIdList(scItemResult)).ifPresent(ids ->{
                if (!ids.isEmpty()){
                    scItemIds.addAll(ids);
                }
            });
            //大于1页时从第二页开始查询
            for (int i = 2;i<=totalPage;i++){
                dbRequest.setPage(i);
                scItemResult = baseDataService.baselineQueryScItemByPageFromDb(dbRequest);
                List<String> scItemIdList = getScItemIdList(scItemResult);
                if (CollectionUtils.isNotEmpty(scItemIdList)){
                    scItemIds.addAll(scItemIdList);
                }
            }
        }else {
            scItemIds.addAll(getScItemIdList(scItemResult));
        }
        return scItemIds;
    }

    //获取总条数
    private static Integer getScItemTotalSize(Object scItemResult){
        return getResult(scItemResult)
                .map(resultJSONObject -> resultJSONObject.getString("total"))
                .map(count -> new BigDecimal(count).intValue())
                .orElse(0);
    }

    //获取货品id列表
    private static List<String> getScItemIdList(Object scItemResult){
        return    getResult(scItemResult)
                .map(resultJSONObject -> resultJSONObject.getJSONArray("content"))
                .map(content -> {
                    List<String> scItemIds = Lists.newArrayList();
                    content.forEach(o -> {
                        JSONObject object = (JSONObject) o;
                        scItemIds.add(object.getString("scItemId"));
                    });
                    return scItemIds;
                }).orElse(null);
    }

    /**
     * 解析货品返回结果json, result -> result
     * {
     *     "result":{
     *         "result":{
     *             "searchResult": [],
     *             "total": 0
     *         }
     *     }
     * }
     * @param scItemResult
     * @return
     */
    private static Optional<JSONObject> getResult(Object scItemResult){
        return Optional.ofNullable(scItemResult).map(obj -> JSON.parseObject(JSON.toJSONString(obj)))
                .map(data -> data.getJSONObject("result"))
                .map(result -> result.getJSONObject("result"));
    }

}
